﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;
using System.Threading;
using System.Text.RegularExpressions;

namespace Performance_Test
{
    class Execuse
    {
        static string nm;

      
   
        //This void is used to create AUTOMATICE name of log file
         public static string CreateFileName_Motion(string perform_type, string symbol, string resolution, string motion)
         {
            string path =  Path.GetDirectoryName(Application.ExecutablePath);
            string filename = path + perform_type + "_" + symbol + "_" + resolution 
                + "_" + motion + "ms" + "_" + GetTimestamp(DateTime.Now) + ".txt";
   
            return filename;
         }
         public static string CreateFileName_Missread(string perform_type, string symbol, string resolution, string distance)
         {
             string path = Path.GetDirectoryName(Application.ExecutablePath);
             string filename = path + perform_type + "_" + symbol + "_" + resolution
                 + "_" + distance + "cm" + "_" + GetTimestamp(DateTime.Now) + ".txt";

             return filename;
         }
         public static string CreateFileName_DOF(string perform_type, string symbol, string resolution, string distance)
         {
             string path = "C:\\";
             string filename = path + perform_type + "_" + symbol + "_" + resolution + "_" 
                 + distance + "cm" + "_" + GetTimestamp(DateTime.Now) + ".txt";
     
             return filename;
         }
         public static string CreateFileName_Pitch(string perform_type, string symbol, string resolution, string pitch)
         {
             string path = "C:\\";
             string filename = path + perform_type + "_" + symbol + "_" + resolution 
                 + "_" + pitch + "degree" + "_" + GetTimestamp(DateTime.Now) + ".txt";
       
             return filename;
         }
         public static string CreateFileName_Skew(string perform_type, string symbol, string resolution, string skew)
         {
             string path = "C:\\";
             string filename = path + perform_type + "_" + symbol + "_" + resolution 
                 + "_" + skew + "degree" + "_" + GetTimestamp(DateTime.Now) + ".txt";
      
             return filename;
         }
         public static string CreateFileName_SweepMode(string perform_type, string symbol
             , string resolution, string distance, string motion)
         {
             string path = "C:\\";
             string filename = path + perform_type + "_" + symbol + "_" + resolution + "_" 
                 + motion + "ms" + distance + "_" + GetTimestamp(DateTime.Now) + ".txt";
   
             return filename;
         }
         public static string CreateFileName_LineEfficiency(string perform_type, string symbol, string resolution, string distance)
         {
             string path = "C:\\";
             string filename = path + perform_type + "_" + symbol + "_" + resolution 
                 + "_" + distance + "cm" + "_" + GetTimestamp(DateTime.Now) + ".txt";
    
             return filename;
         }
         public static string CreateFileName_Presentation(string perform_type, string symbol, string resolution, string motion)
         {
             string path = "C:\\";
             string filename = path + perform_type + "_" + symbol + "_" + resolution + "_" 
                 + motion + "ms" + "_" + GetTimestamp(DateTime.Now) + ".txt";
     
             return filename;
         }
         

         public static void UpdateScanningStatus(string perform_type, string symbol, string resolution, string distance)
         {
             
         }
        //This void is used to write log to file
         public static void LogFile(string filename, string perform_type, string symbol, string resolution, string distance, string motion, string label_num, string pitch, string skew, string scanning_time, string good_read, string incorrect_data, string no_read,string sum_label, string reading_rate, int expected_reading_rate)
        {
            string result = " ";
            int temp = 0,len;

             //format reading_rate to int
            len = reading_rate.Length;
            if (len != 0)
            {
                reading_rate = reading_rate.Substring(0, len - 1);
                temp = Convert.ToInt32(reading_rate);
            }

            result = result_test(temp, expected_reading_rate);
            StreamWriter log;
            if (!File.Exists(filename))
            {
                log = new StreamWriter(filename);
            }
            else
            {
                log = File.AppendText(filename);
            }
            // Write log to the file:
            if (perform_type.Equals("Motion Tolerance"))
            {
                log.WriteLine("Performance type: " + perform_type);
                log.WriteLine("Symbology: " + symbol);
                log.WriteLine("Resolution: " + resolution);
                log.WriteLine("Distance: " + distance + " cm");
                log.WriteLine("Motion: " + motion + " m/s");
                log.WriteLine("The number of labels on belt: " + label_num);
                log.WriteLine("Tilt: Any");
                log.WriteLine("Pitch: 0 degree");
                log.WriteLine("Skew: 10 degree");
                log.WriteLine("Scanning time: " + scanning_time + " ms");
                log.WriteLine("Sum of labels go cross the HH: " + sum_label);
                log.WriteLine("Good Read Data: " + good_read);
                log.WriteLine("Incorrect data: " + incorrect_data);
                log.WriteLine("No read Data: " + no_read);
                log.WriteLine("Reading rate: " + reading_rate + "%    " + "(" + good_read + "/" + sum_label + ")");
                log.WriteLine("Result: " + result);
                log.WriteLine("//***********************RECEIVE DATA******************//");
            }
             if (perform_type.Equals("Missread"))
             {
                 log.WriteLine("Performance type: " + perform_type);
                 log.WriteLine("Symbology: " + symbol);
                 log.WriteLine("Resolution: " + resolution);
                 log.WriteLine("Distance: " + distance + " cm");
               //  log.WriteLine("Motion: " + motion + " m/s");
                 log.WriteLine("The number of testing labels: " + label_num);
                 log.WriteLine("Tilt: Any");
                 log.WriteLine("Pitch: 0 degree");
                 log.WriteLine("Skew: 10 degree");
                 log.WriteLine("Scanning time: " + scanning_time + " ms");
                 log.WriteLine("Sum of labels: " + sum_label);
                 log.WriteLine("Good Read Data: " + good_read);
                 log.WriteLine("Incorrect data: " + incorrect_data);
                 log.WriteLine("No read Data: " + no_read);
                 log.WriteLine("Reading rate: " + reading_rate + "%    " + "(" + good_read + "/" + sum_label + ")");
                 log.WriteLine("Result: " + result);
                 log.WriteLine("//***********************RECEIVE DATA******************//");
             }
            log.WriteLine(TextReceivedData);
            


            // Close the stream:
            log.Close();

        }
         public static string result_test(int _reading_rate, int _expected_reading_rate)
         {
             string _result = " ";
             if (_reading_rate > _expected_reading_rate)
             {
                 _result = "PASSED";
             }
             else
             {
                 _result = "FAILED";
             }
             return _result;
         }

        //this function is used to get timestamp
        public static String GetTimestamp(DateTime value)
        {
            return value.ToString("yyMMddHHmmss");
        }
       
        //this function is used to calculate sum of labels that the HH can read in during scanning time
        public static int SumLabels(float velocity, float distance, long scanning_time)
        {
            if (scanning_time == 0)
            {
                return 1;
            }
            else
            {
                return 1+ (int)Math.Round((velocity / distance * scanning_time/1000), 1);
            }

        }
        public static int SumLabels_Missread(int good_count, int incorrect_count, int missread_count)
        {
            return good_count + incorrect_count + missread_count;

        }



        //this function is used to get double read time out of the HH via service port mode.///
        public static int GetDoubleReadTimeOut(SerialPort ComPort)
        {
            string respond;
            int baud = ComPort.BaudRate;
            if (ComPort.IsOpen)
            {
                //enter service port mode
                ComPort.Write("$S\r");
                 System.Threading.Thread.Sleep(50);
                respond = ComPort.ReadExisting();
                if (respond.Contains("$>"))
                {
                    //***********change baudrate to 115200**********
                    ComPort.BaudRate = 115200;
                    //get value of double read timeout into respond variable
                    ComPort.Write("$cSNDR\r");
                    System.Threading.Thread.Sleep(500);
                    respond = ComPort.ReadExisting();
                    //exist service port mode
                    ComPort.Write("$s\r");
                    System.Threading.Thread.Sleep(500);
                    //**set baudrate back origin**********
                    ComPort.BaudRate = baud;
                    // convert string to int
                    string tx = GetRespondedData(respond.Trim());
                    int Double_Read_Timeout = Convert.ToInt32(ParseHexString(tx)) * 10;

                    return Double_Read_Timeout;

                }
                else
                {
                    return 0;
                }
            }
            else
            {
                MessageBox.Show("Please open COM PORT ");
                return 0;
            }

        }
       
        //this function is used to format responded data from service port
        public static string GetRespondedData(string char_1)
        {
            string last_char;
            
                if (!char_1.Equals(string.Empty))
                {
                    try
                    {
                    last_char = char_1.Substring(0, 2);
                    if (last_char == "$>")
                    {
                        char_1 = char_1.Remove(0, 2);
                        return char_1.Trim();
                    }
                    else
                    {
                        return char_1.Trim();
                    }
                    }
                    catch (Exception ex)
                    {
                                
                          MessageBox.Show(ex.ToString().Trim(), "Error");
                          return char_1.Trim();
                             
                    }
                    
                }
                else
                {
                    return char_1.Trim();
                }
            


        }
        
        //this function is used to convert from hex string to decimal
        private static Decimal ParseHexString(string hexNumber)
        {
            hexNumber = hexNumber.Replace("x", string.Empty);
            long result = 0;
            long.TryParse(hexNumber, System.Globalization.NumberStyles.HexNumber, null, out result);
            return result;
        }

        //this void is useded to calculate time go pass labels
        public static int TimePassLabels(float motion, int label_num)
        {
            float _time;
            _time = 3 / label_num / motion * 1000;

            return (int)_time;

        }
        //Set Double Read Time out for the HH
        public static void SetDoubleReadTimeout(SerialPort ComPort, int time)
        {

            time = (time - 30) / 10;
            //convert int to hex value
            string hexvalue = time.ToString("X");
            string respond;
            int baud = ComPort.BaudRate;
            if (ComPort.IsOpen)
            {
                //enter service port mode
                ComPort.Write("$S\r");
                System.Threading.Thread.Sleep(1000);
                respond = ComPort.ReadExisting();
                if (respond.Contains("$>"))
                {
                    //***********change baudrate to 115200**********
                    ComPort.BaudRate = 115200;
                    //get value of double read timeout into respond variable
                    respond = "$CSNDR" + hexvalue + "\r";
                    ComPort.Write(respond);
                    System.Threading.Thread.Sleep(500);
                    //save and exist service port mode
                    ComPort.Write("$Ar\r");
                    System.Threading.Thread.Sleep(500);
                    //**set baudrate back origin**********
                    ComPort.BaudRate = baud;

                }
                ComPort.DiscardInBuffer();//delete all data in device's received buffer
                ComPort.DiscardOutBuffer();// delete all data in transmit buffer

            }
        }
       

        /// <summary>
        /// This area is used to setup, calculate for all data in Scanning group:
        /// Include: GoodRead data, MissRead Data, Incorrect Data, Sum of labels go cross the HH
        /// </summary>
        /// <param name="observe"></param>
        /// <param name="expected"></param>
        /// <returns></returns>

        public static int GoodReadData(string observe, string expected_1, string expected_2
            , string expected_3, string expected_4, int count)
        {

            int len ;

            string compare_data ="", last_char;
            len = observe.Length;
            last_char = observe.Substring(len - 1, 1);
            if (last_char == "\r")
            {
                compare_data = observe.Substring(22,len-23);

            }
            if (compare_data.Equals(expected_1)||compare_data.Equals(expected_2)||compare_data.Equals(expected_3)||compare_data.Equals(expected_4))
            {
                count++;
            }
            
            return count;
        }
        public static int Good_Count_File(int good_read, string observe, List<string> expected)
        {
            int len;

            string compare_data = "", last_char;
            bool good_temp = false;
            len = observe.Length;
            last_char = observe.Substring(len - 1, 1);

            if (last_char == "\r")
            {
                compare_data = observe.Substring(0,len-1);
              //  count = Regex.Matches(compare_data, "DE").Count;
             //   compare_data = observe.Substring(count * 2, len - (count * 2)-1);
            }
            for (int i=0; i< expected.Count; i++)
            {
                if (expected[i]!=null&&compare_data.Equals(expected[i]))
                {
                    good_temp= true;
                    
                }
                
            }
            if (good_temp)
            {
                good_read++;
            }
            return good_read;

        }
        public static int Incorrect_Count_File(int incorrect_read, string observe, List<string> expected)
        {
            int len;
            bool good_temp = false, incorrect_temp = false;
            string compare_data = "", last_char;
            len = observe.Length;
            last_char = observe.Substring(len - 1, 1);
            if (last_char == "\r")
            {
                compare_data = observe.Substring(0, len - 1);
           //     count = Regex.Matches(compare_data, "DE").Count;
            //    compare_data = observe.Substring(count * 2, len - (count * 2) - 1);

            }
            for (int i = 0; i < expected.Count; i++)
            {
                if (expected[i] != null && compare_data.Equals(expected[i]))
                {
                    good_temp = true;

                }
                if (!compare_data.Equals(expected[i]))
                {
                    incorrect_temp = true;
               
                }
            }
            if (!good_temp && incorrect_temp)
            {
                incorrect_read++;
            }
            return incorrect_read;

        }
        public static int MissRead(int DE_Count)
        {

            if (DE_Count == 0)
            {
                return DE_Count;
            }
            else
            {
                return DE_Count - 1;
            }
        }

        public static int InCorrectReadData(string observe, string expected_1, string expected_2
            , string expected_3, string expected_4, int count)
        {

            int len;
            string compare_data= "", last_char;
            len = observe.Length;
            last_char = observe.Substring(len - 1, 1);
            if (last_char == "\r")
            {
                compare_data = observe.Substring(22, len - 23);

            }
            if (!(compare_data.Equals(expected_1)) && !(compare_data.Equals(expected_2))
                && !(compare_data.Equals(expected_3)) && !(compare_data.Equals(expected_4)))
            {
                count++;
            }

            return count;
        }
        public static int MissReadData(int SumLabels, int GoodRead, int IncorrectRead)
        {
            int missRead;
            missRead = SumLabels - GoodRead- IncorrectRead;
            if (missRead < 0)
            {
                return 0;
            }
            return missRead;
        }
        public static int ReadingRate(int sumlabel, int goodread)
        {
            float readingrate;
            if (sumlabel ==0)
            {
                return 100;
            }
            else
            {
                readingrate = 100* goodread / sumlabel;
                return (int)readingrate;
            }

        }
        
        public static string TextReceivedData
        {
            
            get
            {
                return nm;
            }
            set
            {
                nm = value;
            }
        }

        /// <This area is used to execute for tab Missread>
        /// ///////
        /// </summary>
        /// <param name="ComPort"></param>
        public static void Enable_Disable(SerialPort ComPort)
        {
            Performance_Test v = new Performance_Test();
            
            if (ComPort.IsOpen)
            {
                ComPort.Write("D");
              
                System.Threading.Thread.Sleep(400);
                ComPort.Write("E");
                Execuse.TextReceivedData += "E";
                System.Threading.Thread.Sleep(400);
                
             
            }
        }
       
       
    }
}
